<template>
  <div class="login-container">
    <div class="login-box">
      <div class="logo-container">
        <img src="@/assets/logo.png" alt="Logo" class="logo">
        <h2 class="title">晨诺贝贝管理系统</h2>
      </div>
      <el-form ref="loginForm" :model="loginForm" :rules="formRules" class="login-form">
        <el-form-item prop="username">
          <el-input v-model="loginForm.userAccount" placeholder="请输入用户名" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.userPassword" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" class="login-button">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/userApi';

export default {
  name: 'LoginPage',
  data() {
    return {
      loginForm: {
        userAccount: '',
        userPassword: ''
      },
      formRules: {
        userAccount: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }],
        userPassword: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }]
      }
    };
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          login(this.loginForm)
            .then(response => {
              console.log(response);
              if (response.data.data.token) {
                  // 去除token前后可能存在的空格
                  const token = response.data.data.token.trim();
                  localStorage.setItem('token', token);
                  // 存储用户信息
                  // 确保userInfo包含id字段
                  const apiUser = response.data.data.user;
                  const userInfo = {
                    id: apiUser.id || apiUser.userId, // 处理不同可能的ID字段名
                    username: apiUser.username,
                    userType: apiUser.userType
                  };
                  console.log(userInfo);
                  localStorage.setItem('userInfo', JSON.stringify(userInfo));
                  this.$message.success('登录成功');
                  // 调用App.vue的login方法同步用户信息
                  console.log('验证this.$root.login是否存在:', typeof this.$root.login === 'function');
                  this.$store.dispatch('login', userInfo)
                    .then(async () => {
                      // 登录成功后直接跳转
                      this.$router.push('/');
                    })
                    .catch(storeErr => {
                      console.error('store login action执行失败:', storeErr);
                      this.$message.error('登录过程出错，请重试');
                    });
                } else {
                  console.log(response);
                  this.$message.error('登录失败: ' + (response.data.message || '未知错误'));
              }
            })
            .catch(error => {
              this.$message.error('登录失败: ' + (error.message || '网络错误'));
            });
        }
      });
    }
  }
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(120deg, #e0f2fe, #bfdbfe, #dbeafe, #eff6ff);
  background-size: 400% 400%;
  animation: gradientBG 15s ease infinite;
}

@keyframes gradientBG {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 15px;
  border-radius: 50%;
}

.title {
  font-size: 22px;
  font-weight: bold;
  color: #1e40af;
}

.login-form {
  width: 100%;
}

.login-button {
  width: 100%;
  background: linear-gradient(90deg, #3b82f6, #60a5fa);
  border: none;
  font-size: 16px;
  padding: 12px 0;
}

.login-button:hover {
  background: linear-gradient(90deg, #2563eb, #3b82f6);
}
</style>
